import { CONFIG_KEY, IStoreData, store } from '@/utils/store/store'

type TConfigData = NonNullable<IStoreData['config']>

export interface IConfigStore {
    save: (value: TConfigData) => Promise<void>
    getValue: () => Promise<TConfigData | undefined | null>
}

// 更新图标的辅助函数
const updateIcon = (enabled: boolean) => {
    const iconSuffix = enabled ? '' : '-inactive'
    browser.action.setIcon({
        path: {
            16: `/icon/16${iconSuffix}.png`,
            32: `/icon/32${iconSuffix}.png`,
            48: `/icon/48${iconSuffix}.png`,
            96: `/icon/96${iconSuffix}.png`,
            128: `/icon/128${iconSuffix}.png`,
        },
    })
}

// 配置store
class ConfigStore implements IConfigStore {
    constructor() {
        // 在初始化时判断一次是否启用，启用时更换icon，默认使用未启用icon
        this.getValue().then((config) => {
            // 默认启用状态，只有明确设置为 false 时才显示 inactive 图标
            if (config?.enabled) {
                updateIcon(true)
            } else {
                updateIcon(false)
            }
        })
    }

    // 保存到store
    async save(value: TConfigData) {
        await store.set(CONFIG_KEY, value)
        // 根据 enabled 状态更换icon
        updateIcon(!!value?.enabled)
    }

    // 从store中获取
    async getValue() {
        return (await store.get(CONFIG_KEY)) || {}
    }
}

// 使用配置store hook
export const useConfigStore = (defaultValue?: TConfigData) => {
    const [data, setData] = useState<TConfigData | undefined | null>(
        defaultValue || undefined,
    )
    // 保存到store
    const saveToStore = async (value: TConfigData | undefined | null) => {
        await configStore.save(value || {})
    }

    // 从store中获取
    const getValue = async () => {
        const configData = await configStore.getValue()
        return configData || defaultValue
    }

    // 设置state
    const setState = (value: TConfigData | undefined | null) => {
        setData(value)
        saveToStore(value)
    }

    useEffect(() => {
        getValue().then((value) => {
            setData(value)
        })
    }, [])

    return [data, setState] as const
}

export const configStore = new ConfigStore()
